package com.itboye.mybatis.factory;

import com.itboye.system.helper.ByConfigHelper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.io.IOException;
import java.io.InputStream;


/**
 * Created by hebidu on 16/5/11.
 */
public class DefaultFactory {



    private static DefaultFactory ourInstance;

    private SqlSessionFactory factory;

    public static DefaultFactory getInstance(){
        if(ourInstance == null){
            ourInstance = new DefaultFactory();
        }
        return ourInstance;
    }

    public SqlSessionFactory build() throws IOException {

        if(factory == null) {
            String resource = ByConfigHelper.MyBatisConfigName;
            InputStream inputStream = Resources.getResourceAsStream(resource);
            System.out.println(inputStream.toString());
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        }

        return  factory;
    }

    /**
     * 获取mybatis 的 model 接口方式
     * @return SqlSession
     * @throws IOException
     */
    public <T> T getMapper(Class<T> tClass) throws IOException {
        return  this.build().openSession().getMapper(tClass);
    }

    /**
     * 获取Sql Session
     * @return SqlSession
     * @throws IOException
     */
    public SqlSession getSqlSession() throws IOException {
        return  this.build().openSession();
    }


    private DefaultFactory() {

    }


}
